<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>密钥管理 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
        }
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        .btn {
            transition: all 0.3s ease;
        }
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
        }
        .input-field {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        .input-field:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        .table-row {
            transition: all 0.2s ease;
        }
        .table-row:hover {
            background-color: rgba(59, 130, 246, 0.05);
        }
        .back-btn {
            transition: all 0.3s ease;
        }
        .back-btn:hover {
            background-color: rgba(59, 130, 246, 0.1);
        }
        .status-badge {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-active {
            background-color: rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        .status-inactive {
            background-color: rgba(156, 163, 175, 0.2);
            color: #6b7280;
        }
        .masked-text {
            font-family: 'Courier New', monospace;
        }
        .modal-backdrop {
            backdrop-filter: blur(2px);
        }
        .strength-bar {
            height: 4px;
            border-radius: 2px;
        }
        .strength-weak {
            background-color: #ef4444;
        }
        .strength-medium {
            background-color: #f59e0b;
        }
        .strength-strong {
            background-color: #10b981;
        }
    </style>
</head>
<body class="p-6">
    <!-- 通用组件脚本 -->
    <script src="common.js"></script>
    <div class="container mx-auto">
        <!-- 页面标题和返回按钮 -->
        <div class="mb-6 flex items-center justify-between">
            <h1 class="text-3xl font-bold text-gray-800">密钥管理</h1>
            <a href="index.html" class="back-btn px-4 py-2 rounded-lg flex items-center gap-2 text-gray-600">
                <i class="fas fa-arrow-left"></i>
                <span>返回首页</span>
            </a>
        </div>

        <!-- 操作栏 -->
        <div class="card p-6 mb-6">
            <div class="flex flex-wrap justify-between items-center gap-4">
                <div class="flex flex-wrap gap-2">
                    <select class="input-field px-4 py-2" id="keyTypeFilter">
                        <option value="">所有密钥类型</option>
                        <option value="主密钥">主密钥</option>
                        <option value="KEK">KEK</option>
                        <option value="DEK">DEK</option>
                    </select>
                    <select class="input-field px-4 py-2" id="algorithmFilter">
                        <option value="">所有算法</option>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                    <input type="text" class="input-field px-4 py-2" id="searchInput" placeholder="搜索密钥...">
                </div>
                <div class="flex flex-wrap gap-2">
                    <button class="btn btn-primary px-4 py-2 rounded-lg" onclick="openAddKeyModal()">
                        <i class="fas fa-plus"></i> 新增密钥
                    </button>
                    <button class="btn btn-primary px-4 py-2 rounded-lg" onclick="generateBackup()">
                        <i class="fas fa-download"></i> 备份密钥
                    </button>
                </div>
            </div>
        </div>

        <!-- 密钥表格 -->
        <div class="card p-6">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥ID</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥名称</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥类型</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">算法</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">长度</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">有效期</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">状态</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作</th>
                        </tr>
                    </thead>
                    <tbody id="keysTableBody">
                        <!-- 密钥数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 新增密钥模态框 -->
    <div id="addKeyModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 modal-backdrop">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">新增密钥</h3>
                <button onclick="closeAddKeyModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="addKeyForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥名称</label>
                    <input type="text" name="name" class="input-field w-full px-4 py-2" required placeholder="请输入密钥名称">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥类型</label>
                    <select id="keyType" name="type" class="input-field w-full px-4 py-2" required>
                        <option value="">请选择密钥类型</option>
                        <option value="主密钥">主密钥</option>
                        <option value="KEK">KEK</option>
                        <option value="DEK">DEK</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">算法</label>
                    <select name="algorithm" class="input-field w-full px-4 py-2" required>
                        <option value="">请选择算法</option>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥长度</label>
                    <input type="number" name="length" class="input-field w-full px-4 py-2" min="128" max="4096" required placeholder="请输入密钥长度">
                </div>
                <div id="keyLengthContainer" class="hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-1">主秘钥KEY</label>
                    <textarea name="key" class="input-field w-full px-4 py-2" rows="4" placeholder="请输入主秘钥KEY"></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">有效期</label>
                    <input type="date" name="expiry" class="input-field w-full px-4 py-2" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用途</label>
                    <input type="text" name="purpose" class="input-field w-full px-4 py-2" required placeholder="请输入密钥用途">
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeAddKeyModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg">创建密钥</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 密钥详情模态框 -->
    <div id="keyDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 modal-backdrop">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">密钥详情</h3>
                <button onclick="closeKeyDetailModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="keyDetailContent" class="space-y-4">
                <!-- 密钥详情内容将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <!-- 编辑密钥模态框 -->
    <div id="editKeyModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 modal-backdrop">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">编辑密钥</h3>
                <button onclick="closeEditKeyModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="editKeyForm" class="space-y-4">
                <input type="hidden" name="id" id="editKeyId">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥名称</label>
                    <input type="text" name="name" id="editKeyName" class="input-field w-full px-4 py-2" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥类型</label>
                    <select name="type" id="editKeyType" class="input-field w-full px-4 py-2" required>
                        <option value="主密钥">主密钥</option>
                        <option value="KEK">KEK</option>
                        <option value="DEK">DEK</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">算法</label>
                    <select name="algorithm" id="editKeyAlgorithm" class="input-field w-full px-4 py-2" required>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">密钥长度</label>
                    <input type="number" name="length" id="editKeyLength" class="input-field w-full px-4 py-2" min="128" max="4096" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">有效期</label>
                    <input type="date" name="expiry" id="editKeyExpiry" class="input-field w-full px-4 py-2" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用途</label>
                    <input type="text" name="purpose" id="editKeyPurpose" class="input-field w-full px-4 py-2" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                    <select name="status" id="editKeyStatus" class="input-field w-full px-4 py-2" required>
                        <option value="active">启用</option>
                        <option value="inactive">禁用</option>
                    </select>
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeEditKeyModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg">保存修改</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteConfirmModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 modal-backdrop">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-red-600">确认删除</h3>
                <button onclick="closeDeleteConfirmModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <p class="mb-4">确定要删除此密钥吗？此操作不可撤销。</p>
            <div class="flex justify-end gap-2">
                <button onclick="closeDeleteConfirmModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                <button onclick="confirmDelete()" class="px-4 py-2 rounded-lg bg-red-100 text-red-600 border border-red-200 hover:bg-red-200">删除密钥</button>
            </div>
        </div>
    </div>

    <script>
        // 当前操作的密钥ID
        let currentKeyId = null;

        // 初始化数据
        function initData() {
            showLoading();
            // 模拟网络延迟
            setTimeout(() => {
                // 初始化密钥数据（如果不存在）
                if (!localStorage.getItem('keys')) {
                    const initialKeys = [
                        { id: 'KMS-001', name: '应用主密钥', type: '主密钥', algorithm: 'SM2', length: 256, expiry: '2025-12-31', status: 'active', purpose: '应用加密' },
                        { id: 'KMS-002', name: '数据加密密钥', type: 'KEK', algorithm: 'AES', length: 128, expiry: '2024-12-31', status: 'active', purpose: '数据加密' },
                        { id: 'KMS-003', name: '文件加密密钥', type: 'DEK', algorithm: 'SM4', length: 256, expiry: '2025-06-30', status: 'inactive', purpose: '文件加密' },
                        { id: 'KMS-004', name: '用户数据密钥', type: 'DEK', algorithm: 'AES', length: 256, expiry: '2025-03-31', status: 'active', purpose: '用户数据保护' },
                        { id: 'KMS-005', name: '备份加密密钥', type: 'KEK', algorithm: 'RSA', length: 2048, expiry: '2026-01-31', status: 'active', purpose: '数据备份加密' }
                    ];
                    localStorage.setItem('keys', JSON.stringify(initialKeys));
                }
                hideLoading();
            }, 500);
        }

        // 加载密钥表格
        function loadKeys() {
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const tbody = document.getElementById('keysTableBody');
                tbody.innerHTML = '';

                keys.forEach(key => {
                    const row = document.createElement('tr');
                    row.className = 'table-row border-b border-gray-100';
                    row.innerHTML = `
                        <td class="py-3 px-4 font-mono">${key.id || '未知ID'}</td>
                        <td class="py-3 px-4">${key.name || '未命名密钥'}</td>
                        <td class="py-3 px-4">${key.type || '未知类型'}</td>
                        <td class="py-3 px-4">${key.algorithm || '未知算法'}</td>
                        <td class="py-3 px-4">${key.length || 0}</td>
                        <td class="py-3 px-4">${key.expiry || '永不过期'}</td>
                        <td class="py-3 px-4">
                            <span class="status-badge ${(key.status === 'active') ? 'status-active' : 'status-inactive'}">
                                ${(key.status === 'active') ? '启用' : '禁用'}
                            </span>
                        </td>
                        <td class="py-3 px-4">
                            <div class="flex gap-2">
                                <button onclick="toggleKeyStatus('${key.id}')" class="text-yellow-600 hover:text-yellow-800 tooltip" title="${key.status === 'active' ? '禁用' : '启用'}">
                                    <i class="fas fa-toggle-${key.status === 'active' ? 'on' : 'off'}"></i>
                                </button>
                                <button onclick="viewKey('${key.id}')" class="text-gray-600 hover:text-gray-800 tooltip" title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button onclick="editKey('${key.id}')" class="text-blue-600 hover:text-blue-800 tooltip" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="openDeleteConfirmModal('${key.id}')" class="text-red-600 hover:text-red-800 tooltip" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                hideLoading();
            }, 300);
        }

        // 搜索和筛选功能
        function setupSearchAndFilter() {
            const searchInput = document.getElementById('searchInput');
            const keyTypeFilter = document.getElementById('keyTypeFilter');
            const algorithmFilter = document.getElementById('algorithmFilter');

            function filterKeys() {
                const searchTerm = searchInput.value.toLowerCase();
                const keyType = keyTypeFilter.value;
                const algorithm = algorithmFilter.value;
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const tbody = document.getElementById('keysTableBody');
                tbody.innerHTML = '';

                const filteredKeys = keys.filter(key => {
                    const matchesSearch = key.name.toLowerCase().includes(searchTerm) || key.id.toLowerCase().includes(searchTerm);
                    const matchesType = keyType ? key.type === keyType : true;
                    const matchesAlgorithm = algorithm ? key.algorithm === algorithm : true;
                    return matchesSearch && matchesType && matchesAlgorithm;
                });

                if (filteredKeys.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="8" class="py-8 text-center text-gray-500">
                                <i class="fas fa-search text-4xl mb-2"></i>
                                <p>没有找到匹配的密钥</p>
                            </td>
                        </tr>
                    `;
                    return;
                }

                filteredKeys.forEach(key => {
                    const row = document.createElement('tr');
                    row.className = 'table-row border-b border-gray-100';
                    row.innerHTML = `
                        <td class="py-3 px-4 font-mono">${key.id}</td>
                        <td class="py-3 px-4">${key.name}</td>
                        <td class="py-3 px-4">${key.type}</td>
                        <td class="py-3 px-4">${key.algorithm}</td>
                        <td class="py-3 px-4">${key.length}</td>
                        <td class="py-3 px-4">${key.expiry}</td>
                        <td class="py-3 px-4">
                            <span class="status-badge ${key.status === 'active' ? 'status-active' : 'status-inactive'}">
                                ${key.status === 'active' ? '启用' : '禁用'}
                            </span>
                        </td>
                        <td class="py-3 px-4">
                            <div class="flex gap-2">
                                <button onclick="toggleKeyStatus('${key.id}')" class="text-yellow-600 hover:text-yellow-800 tooltip" title="${key.status === 'active' ? '禁用' : '启用'}">
                                    <i class="fas fa-toggle-${key.status === 'active' ? 'on' : 'off'}"></i>
                                </button>
                                <button onclick="viewKey('${key.id}')" class="text-gray-600 hover:text-gray-800 tooltip" title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button onclick="editKey('${key.id}')" class="text-blue-600 hover:text-blue-800 tooltip" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="openDeleteConfirmModal('${key.id}')" class="text-red-600 hover:text-red-800 tooltip" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            }

            searchInput.addEventListener('input', filterKeys);
            keyTypeFilter.addEventListener('change', filterKeys);
            algorithmFilter.addEventListener('change', filterKeys);
        }

        // 新增密钥
        function openAddKeyModal() {
            document.getElementById('addKeyModal').classList.remove('hidden');
        }

        function closeAddKeyModal() {
            document.getElementById('addKeyModal').classList.add('hidden');
            document.getElementById('addKeyForm').reset();
        }

        // 表单提交事件
        document.getElementById('addKeyForm').addEventListener('submit', (e) => {
            e.preventDefault();
            
            // 表单验证
            const form = e.target;
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            
            const formData = new FormData(e.target);
            const key = {
                id: `KMS-${Date.now().toString(36)}${Math.random().toString(36).substr(2, 5)}`,
                name: formData.get('name'),
                type: formData.get('type'),
                algorithm: formData.get('algorithm'),
                length: parseInt(formData.get('length')),
                expiry: formData.get('expiry'),
                status: 'active',
                purpose: formData.get('purpose'),
                createdAt: new Date().toISOString().split('T')[0]
            };

            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                keys.push(key);
                localStorage.setItem('keys', JSON.stringify(keys));

                closeAddKeyModal();
                loadKeys();
                showToast('密钥创建成功！');
                hideLoading();
            }, 800);
        });

        // 切换密钥状态
        function toggleKeyStatus(keyId) {
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const keyIndex = keys.findIndex(k => k.id === keyId);
                if (keyIndex !== -1) {
                    keys[keyIndex].status = keys[keyIndex].status === 'active' ? 'inactive' : 'active';
                    localStorage.setItem('keys', JSON.stringify(keys));
                    loadKeys();
                    showToast(`密钥已${keys[keyIndex].status === 'active' ? '启用' : '禁用'}！`);
                }
                hideLoading();
            }, 500);
        }

        // 查看密钥
        function viewKey(keyId) {
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const key = keys.find(k => k.id === keyId);
                if (key) {
                    const modal = document.getElementById('keyDetailModal');
                    const content = document.getElementById('keyDetailContent');
                    content.innerHTML = `
                        <div class="space-y-3">
                            <div class="flex justify-between">
                                <span class="text-gray-600">密钥ID:</span>
                                <span class="font-mono font-medium">${key.id}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">密钥名称:</span>
                                <span>${key.name}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">密钥类型:</span>
                                <span>${key.type}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">算法:</span>
                                <span>${key.algorithm}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">密钥长度:</span>
                                <span>${key.length} bits</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">有效期:</span>
                                <span>${key.expiry}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">状态:</span>
                                <span class="status-badge ${key.status === 'active' ? 'status-active' : 'status-inactive'}">
                                    ${key.status === 'active' ? '启用' : '禁用'}
                                </span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">用途:</span>
                                <span>${key.purpose}</span>
                            </div>
                            ${key.createdAt ? `
                            <div class="flex justify-between">
                                <span class="text-gray-600">创建时间:</span>
                                <span>${key.createdAt}</span>
                            </div>
                            ` : ''}
                        </div>
                        <div class="mt-4 pt-4 border-t border-gray-200">
                            <button onclick="closeKeyDetailModal()" class="w-full btn btn-primary py-2 rounded-lg">关闭</button>
                        </div>
                    `;
                    modal.classList.remove('hidden');
                }
                hideLoading();
            }, 300);
        }

        // 关闭密钥详情模态框
        function closeKeyDetailModal() {
            document.getElementById('keyDetailModal').classList.add('hidden');
        }

        // 编辑密钥
        function editKey(keyId) {
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const key = keys.find(k => k.id === keyId);
                if (key) {
                    document.getElementById('editKeyId').value = key.id;
                    document.getElementById('editKeyName').value = key.name;
                    document.getElementById('editKeyType').value = key.type;
                    document.getElementById('editKeyAlgorithm').value = key.algorithm;
                    document.getElementById('editKeyLength').value = key.length;
                    document.getElementById('editKeyExpiry').value = key.expiry;
                    document.getElementById('editKeyPurpose').value = key.purpose;
                    document.getElementById('editKeyStatus').value = key.status;
                    document.getElementById('editKeyModal').classList.remove('hidden');
                }
                hideLoading();
            }, 300);
        }

        // 关闭编辑密钥模态框
        function closeEditKeyModal() {
            document.getElementById('editKeyModal').classList.add('hidden');
            document.getElementById('editKeyForm').reset();
        }

        // 编辑密钥表单提交
        document.getElementById('editKeyForm').addEventListener('submit', (e) => {
            e.preventDefault();
            
            // 表单验证
            const form = e.target;
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }
            
            const formData = new FormData(e.target);
            const keyId = formData.get('id');
            
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const keyIndex = keys.findIndex(k => k.id === keyId);
                if (keyIndex !== -1) {
                    keys[keyIndex] = {
                        ...keys[keyIndex],
                        name: formData.get('name'),
                        type: formData.get('type'),
                        algorithm: formData.get('algorithm'),
                        length: parseInt(formData.get('length')),
                        expiry: formData.get('expiry'),
                        purpose: formData.get('purpose'),
                        status: formData.get('status')
                    };
                    localStorage.setItem('keys', JSON.stringify(keys));
                    closeEditKeyModal();
                    loadKeys();
                    showToast('密钥更新成功！');
                }
                hideLoading();
            }, 800);
        });

        // 打开删除确认模态框
        function openDeleteConfirmModal(keyId) {
            currentKeyId = keyId;
            document.getElementById('deleteConfirmModal').classList.remove('hidden');
        }

        // 关闭删除确认模态框
        function closeDeleteConfirmModal() {
            currentKeyId = null;
            document.getElementById('deleteConfirmModal').classList.add('hidden');
        }

        // 确认删除
        function confirmDelete() {
            if (!currentKeyId) return;
            
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const updatedKeys = keys.filter(key => key.id !== currentKeyId);
                localStorage.setItem('keys', JSON.stringify(updatedKeys));
                closeDeleteConfirmModal();
                loadKeys();
                showToast('密钥删除成功！');
                hideLoading();
            }, 800);
        }

        // 生成备份
        function generateBackup() {
            showLoading();
            setTimeout(() => {
                const keys = JSON.parse(localStorage.getItem('keys')) || [];
                const templates = JSON.parse(localStorage.getItem('templates')) || [];
                const distributionRequests = JSON.parse(localStorage.getItem('distributionRequests')) || [];
                const keyRequests = JSON.parse(localStorage.getItem('keyRequests')) || [];
                
                const backupData = JSON.stringify({
                    keys,
                    templates,
                    distributionRequests,
                    keyRequests,
                    backupDate: new Date().toISOString(),
                    version: '1.0'
                }, null, 2);
                
                const blob = new Blob([backupData], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `kms-backup-${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showToast('备份生成成功！');
                hideLoading();
            }, 1000);
        }

        // 设置默认日期为明天
        document.addEventListener('DOMContentLoaded', () => {
            const tomorrow = new Date();
            tomorrow.setDate(tomorrow.getDate() + 1);
            const formattedDate = tomorrow.toISOString().split('T')[0];
            
            const expiryInputs = document.querySelectorAll('input[name="expiry"]');
            expiryInputs.forEach(input => {
                input.min = formattedDate;
                input.value = formattedDate;
            });
            
            // 监听keyType变化，控制keyLengthContainer的显示/隐藏
            const keyTypeSelect = document.getElementById('keyType');
            const keyLengthContainer = document.getElementById('keyLengthContainer');
            
            function updateKeyLengthContainerVisibility() {
                if (keyTypeSelect.value === 'DEK') {
                    keyLengthContainer.classList.remove('hidden');
                } else {
                    keyLengthContainer.classList.add('hidden');
                }
            }
            
            // 初始加载时检查
            updateKeyLengthContainerVisibility();
            
            // 添加change事件监听
            keyTypeSelect.addEventListener('change', updateKeyLengthContainerVisibility);
            
            initData();
            loadKeys();
            setupSearchAndFilter();
        });

        // 点击模态框外部关闭模态框
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('modal-backdrop')) {
                closeAddKeyModal();
                closeKeyDetailModal();
                closeEditKeyModal();
                closeDeleteConfirmModal();
            }
        });

        // 按下ESC键关闭所有模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                closeAddKeyModal();
                closeKeyDetailModal();
                closeEditKeyModal();
                closeDeleteConfirmModal();
            }
        });
    </script>
</body>
</html>